package gold.digger;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC202 {
    public long startExecuteTime = System.currentTimeMillis();


    public boolean isHappy(int n) {
        if (isTimesTen(n)) {
            return true;
        }

        Set<Long> exist = new HashSet<>();
        exist.add(new Long(n));
        long num = getNext(n);
        while (!exist.contains(num)) {
            if (isTimesTen(num)) {
                return true;
            }

            exist.add(num);
            num = getNext(num);
        }

        return false;
    }

    public long getNext(long num) {
        long next = 0;
        while (num > 0) {
            next += (num % 10) * (num % 10);
            num /= 10;
        }
        return next;
    }

    boolean isTimesTen(long num) {
        while (num > 1) {
            if (num % 10 != 0) {
                return false;
            }
            num /= 10;
        }

        return true;
    }


    public static void main(String[] args) {
        LC202 an = new LC202();
        String test = "abbbbacd";
        System.out.println(an.isHappy(19));

        System.out.println("\nanswer total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
